package kevin.framework.basic.common.utils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.FieldInfo;
import com.alibaba.fastjson.util.TypeUtils;

import kevin.framework.basic.common.ui.ClientButton;

/**
 * @ClassName: PagingResult
 * @Description: TODO
 * @author kevin.huang
 * @date 2016年4月4日 下午5:02:58
 * @param <T>
 */
public class PagingResult<T> {

	private int currentPage;

	private long totalSize;

	private List<T> resultList = new ArrayList<T>();

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public long getTotalSize() {
		return totalSize;
	}

	public void setTotalSize(long totalSize) {
		this.totalSize = totalSize;
	}

	public List<T> getResultList() {
		return resultList;
	}

	public void setResultList(List<T> resultList) {
		this.resultList = resultList;
	}

	/**
	 * @Title: toJSONObject @Description: TODO @param clazz @param
	 * excludeFields @param autdValid @param buttons @return @throws
	 * IllegalAccessException @throws InvocationTargetException @throws
	 */
	public JSONObject toJSONObject(HttpServletRequest request, Class<T> clazz, Set<String> excludeFields,
			IControlCommon<T> controll, List<ClientButton> buttons)
			throws IllegalAccessException, InvocationTargetException, Exception {
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("currentPage", getCurrentPage());
		jsonObj.put("totalSize", getTotalSize());
		JSONArray jsonArray = new JSONArray();
		List<FieldInfo> getters = TypeUtils.computeGetters(clazz, null);
		int size = getters.size();
		for (T obj : getResultList()) {
			JSONObject json = new JSONObject(size);
			for (FieldInfo field : getters) {
				String fieldName = field.name;
				if (excludeFields == null || !excludeFields.contains(fieldName)) {
					Object value = field.get(obj);
					Object jsonValue = JSONObject.toJSON(value);
					json.put(fieldName, jsonValue);
				}
			}
			controll.extGridResult(obj, json);
			// 生成按钮
			if (buttons != null && buttons.size() > 0) {
				JSONArray btnJsonArr = new JSONArray();
				for (ClientButton btn : buttons) {
					/*
					 * if(controll.hasDataPrivilage(obj, request, btn.getCmd())){
					 * btn.setDisabled(false); controll.buttonCreateHanlder(obj, btn);
					 * btn.setParams("privilage", "1"); }else{ btn.setParams("privilage", "0");
					 * btn.setDisabled(true); }
					 */

					btnJsonArr.add(btn.copy().toJSONObject(request, controll, obj));
				}
				json.put("toolbar", btnJsonArr);
			}
			jsonArray.add(json);
		}
		jsonObj.put("resultList", jsonArray);
		return jsonObj;
	}
}
